import {
  build,
  create,
  calculate,
  payment,
  check_shipping
} from '../../../api/order';
import {
  getInfo
} from '../../../api/member'
import {
  submit,
  query
} from '../../../api/payment';
import {
  list
} from '../../../api/address';
import {
  find as shopFind, list as shopList
} from '../../../api/shop.js';
import { getInfo as getEnterpriseInfo } from '../../../api/enterprise'

const util = require('../../../utils/util.js')
const app = getApp();
Page({
  data: {
    calculate: {},
    delivery: {
      title: ''
    },
    deliveryTimeSwitch: app.DELIVERY_TIME,
    barginBuyId: '',
    groupBuyId: '',
    deliveryType: false,
    couponsType: false,
    coupons: null,
    submitType: false,
    address: null,
    order_Details: {
      address: null
    },
    sn: '',
    orderId: '',
    amount: 0,
    consignee: '',
    shippingMethods: [],
    shippingMethod: '',
    distribution: [],
    paymentVo: [],
    point: '',
    check_shippingData: [],
    couponCodeName: '',
    packageType: false,
    weexDate: [{ title: '请选择配送日期' }],
    weexTime: '',
    waterType: false,
    waterPrice: 0,
    waterStatus: false,
    tabNumStatus: false,
    bomType: 0,
    siteType: false,
    shopId: '',
    shopName: '请选择提货点',
    shopAddress: '',
    shopIndex: '0',
    phone: '',
    addressConsignee: '',
    addressPhone: '',
    shippingMethodType: false,
    distributionType: false,
    liveId: '',
    onlinePayment: false,
    offlinePayment: false,
    payMethodType: '',
    customerInfo: {},
    shippingClickFlag: true, //防双击
    platform: app.globalData.platform,
    deliveryTime: null,
    urgent: 0,
    estimateDate: null,
    deliveryTimeFlag: false,
    placeOrder: app.globalData.placeOrder,
    tabNumber: null,
    lat: null,
    lng: null,
  },
  onShow() {
    this.data.onlinePayment = app.globalData.onlinePayment
    this.data.offlinePayment = app.globalData.offlinePayment
    if (this.data.onlinePayment == true && this.data.offlinePayment == false) {
      this.data.payMethodType = 'weixinPay'
    } else if (this.data.onlinePayment == false && this.data.offlinePayment == true) {
      this.data.payMethodType = 'facePayPlugin'
    } else {
      this.data.payMethodType = ''
    }
    this.setData({
      onlinePayment: this.data.onlinePayment,
      offlinePayment: this.data.offlinePayment,
      payMethodType: this.data.payMethodType,
      deliveryTimeSwitch:app.DELIVERY_TIME,
    })
    wx.onAppShow((options) => {
      if (options.scene === 1037 || options.scene === 1038) {
        wx.showLoading({
          title: '查询支付状态',
        })
        if (!util.isNull(options.referrerInfo.extraData)) {
          const { extraData } = options.referrerInfo
          if (extraData.status == 'success') {
            wx.hideLoading()
            wx.redirectTo({
              url: '/pages/goods/submit/complete?id=' + this.data.orderId,
            })
          } else {
            this.data.shippingClickFlag = true //开启防双击
            wx.hideLoading()
            wx.showToast({
              title: '支付失败',
              icon: 'none'
            })
          }
        }else{
          this.queryClick()
          wx.hideLoading()
        }
      }
    })
  },
  onLoad: function (options) {
    if (options.liveId) {
      this.data.liveId = options.liveId
    }
    if (options.orderType) {
      if (options.orderType == 'takeout') {
        this.data.shippingMethod = 0
      } else if (options.orderType == 'takein') {
        this.data.shippingMethod = 1
      }
      this.setData({
        shippingMethod: this.data.shippingMethod
      })
    }
    if (options.shopId) {
      this.data.shopId = options.shopId
      this.setData({
        shopId: this.data.shopId
      })
    }
    this.loadBuild(options)
    this.getEnterpriseInfo()
  },
  getEnterpriseInfo(){
    getEnterpriseInfo().then(res=>{
      const shippingConfigs = JSON.parse(res.data.shippingConfig)
      let deliveryTimeFlag =  shippingConfigs.deliveryTime ? shippingConfigs.deliveryTime : app.DELIVERY_TIME == 1
      this.setData({
        deliveryTimeFlag: deliveryTimeFlag
      })
    })
  },
  getInfo() {
    getInfo().then(res => {
      this.data.consignee = res.data.member.name
      this.data.phone = res.data.member.mobile
      this.setData({
        consignee: this.data.consignee,
        phone: this.data.phone
      })
    })
  },
  getShopList() {
    let params = {
      mchId: app.globalData.mchId,
    }
    if ((!util.isNull(this.data.lat) && !util.isNull(this.data.lng)) || (!util.isNull(app.globalData.lat) && !util.isNull(app.globalData.lng))) {
      params.lat = this.data.lat || app.globalData.lat
      params.lng = this.data.lng || app.globalData.lng
    }
    shopList(params).then(res => {
      if (res.data.length > 0) {
        let params = {
          detail: {
            from: res.data[0],
            shopIndex: 0
          }
        }
        this.completeSite(params)
      }
    })
  },
  deliveryTimeClick() {
    this.selectComponent('#deliveryTime').deliveryTimeClick()
  },
  getCustomerInfo(item) {
    if (item.detail.member.paymentPluginId == 'debtPayPlugin') {
      wx.showToast({
        icon: "none",
        title: '月结客户不支持代付',
      })
      return false
    }
    if (this.data.shopId == '' && this.data.shopId == null) {
      wx.showToast({
        icon: "none",
        title: '请选择门店',
      })
      return false
    }
    this.data.paymentVo = []
    this.data.customerInfo = item.detail
    this.data.calculate.memberId = this.data.customerInfo.member.id
    this.data.calculate.receiverId = this.data.customerInfo.receiver.id
    this.data.phone = this.data.customerInfo.member.mobile
    this.data.consignee = this.data.customerInfo.member.name
    this.data.calculate.shopId = this.data.shopId
    this.data.calculate.shopName = this.data.shopName
    this.setData({
      customerInfo: this.data.customerInfo,
      calculate: this.data.calculate,
      paymentVo: this.data.paymentVo,
      phone: this.data.phone,
      consignee: this.data.consignee,
      shopId: this.data.calculate.shopId,
      shopName: this.data.calculate.shopName
    })
    this.calculateClick(this.data.calculate)
  },
  substitutePayment() {
    this.selectComponent("#valetPopup").appear();
  },
  getOnlinePayment() {
    this.data.onlinePayment = app.globalData.onlinePayment
    this.setData({
      onlinePayment: app.globalData.onlinePayment
    })
  },
  completeDelivery: function (e) {
    var _this = this
    this.data.deliveryType = false
    if (e.detail.completeDelivery.title == '普通快递') {
      _this.data.calculate.shippingMethod = 0
      _this.data.shippingMethod = 0
      _this.data.calculate.consignee = _this.data.address.consignee
      _this.data.calculate.phone = _this.data.address.phone
    } else if (e.detail.completeDelivery.title == '到店提货') {
      _this.data.calculate.shippingMethod = 1
      _this.data.shippingMethod = 1
      _this.data.calculate.consignee = _this.data.consignee
      _this.data.calculate.phone = _this.data.phone
    } else if (e.detail.completeDelivery.title == '同城配送') {
      _this.data.calculate.shippingMethod = 2
      _this.data.shippingMethod = 2
      _this.data.calculate.consignee = _this.data.address.consignee
      _this.data.calculate.phone = _this.data.address.phone
    }
    this.setData({
      delivery: e.detail.completeDelivery,
      deliveryType: _this.data.deliveryType,
      shippingMethod: _this.data.shippingMethod,
    })
  },
  cencleDelivery() {
    this.data.deliveryType = false
    this.setData({
      deliveryType: this.data.deliveryType
    })
  },
  couponsClick() {
    if (this.data.calculate.discount == 0) {
      wx.showToast({
        title: '暂无优惠',
        icon: "none",
      })
    } else {
      this.data.couponsType = true
      this.setData({
        couponsType: this.data.couponsType
      })
    }
  },
  completecoupons: function (e) {
    this.data.couponsType = false
    this.setData({
      coupons: e.detail.completecoupons,
      couponsType: this.data.couponsType
    })
  },
  cenclecoupons() {
    this.data.couponsType = false
    this.setData({
      couponsType: this.data.couponsType
    })
  },
  check_shippingClick() {
    if (this.data.shippingClickFlag == true) {
      this.data.shippingClickFlag = false
      var _this = this
      if (_this.data.payMethodType == '' && _this.data.amount > 0) {
        wx.showToast({
          icon: "none",
          title: '请选择支付方式',
        })
        this.data.shippingClickFlag = true //开启防双击
        return;
      }
      if (_this.data.distributionType == false) {
        if (_this.data.phone == '') {
          wx.showToast({
            icon: "none",
            title: '请输入提货人手机号',
          })
          this.data.shippingClickFlag = true //开启防双击
          return;
        }
        if (util.isNull(_this.data.tabNumber) && app.DESK_TYPE == 1 && _this.data.tabNumStatus == true) {
          wx.showToast({
            icon: "none",
            title: '请选择桌号',
          })
          this.data.shippingClickFlag = true //开启防双击
          return;
        }
        // if (_this.data.consignee == '') {
        //   wx.showToast({
        //     icon: "none",
        //     title: '请输入提货人姓名',
        //   })
        //   this.data.shippingClickFlag = true //开启防双击
        //   return;
        // }
        if (_this.data.shopId == '') {
          wx.showToast({
            icon: "none",
            title: '请选择提货门店',
          })
          this.data.shippingClickFlag = true //开启防双击
          return;
        }
      } else {
        if (util.isNull(_this.data.calculate.receiverId)) {
          wx.showToast({
            icon: "none",
            title: '请选择收货地址',
          })
          this.data.shippingClickFlag = true //开启防双击
          return;
        }
      }
      check_shipping(_this.data.calculate, {
        receiverId: _this.data.calculate.receiverId
      }).then(res => {
        this.data.shippingClickFlag = false
        if (res.data.length == 0) {
          _this.createClick()
        } else {
          _this.data.check_shippingData = res.data
          this.data.submitType = true;
          this.setData({
            submitType: this.data.submitType,
            check_shippingData: _this.data.check_shippingData
          })
        }
      }).catch(err => {
        this.data.shippingClickFlag = true //开启防双击
      })
    }
  },
  // 创建订单
  createClick() {
    var _this = this
    if (_this.data.bomType == 1) {
      if (_this.data.weexTime == '') {
        wx.showToast({
          icon: "none",
          title: '请选择配送时间',
        })
        this.data.shippingClickFlag = true //开启防双击
        return
      } else {
        _this.data.calculate.weekTime = _this.data.weexTime
      }
    }
    if (_this.data.distributionType == true) {
      if (_this.data.address == null) {
        this.data.shippingClickFlag = true
        wx.showToast({
          title: '请选择地址',
        })
        this.data.shippingClickFlag = true //开启防双击
      } else {
        _this.data.shippingMethod = 0
        _this.data.calculate.shippingMethod = 0
      }
    } else if (_this.data.distributionType == false) {
      if (_this.data.phone == '') {
        wx.showToast({
          title: '请填写电话',
        })
        this.data.shippingClickFlag = true //开启防双击
      } else {
        _this.data.shippingMethod = 1
        _this.data.calculate.shippingMethod = 1
      }
    }
    _this.data.calculate.shippingMethod = _this.data.shippingMethod
    create(_this.data.calculate, {
      shippingMethod: _this.data.shippingMethod,
    }).then(res => {
      if (res.type == 'success') {
        _this.data.orderId = res.data.id
        if (res.data.paymentStatus == 1) {
          wx.redirectTo({
            url: '/pages/goods/submit/complete?id=' + _this.data.orderId,
          })
        } else {
          _this.paymentClick(res)
        }
      }
    }).catch(err => {
      console.log(err);
      this.data.shippingClickFlag = true //开启防双击
    })
  },
  paymentClick(data) {
    var _this = this
    var payMethosType = ''
    if (_this.data.payMethodType == 'facePayPlugin') {
      payMethosType = 'facePayPlugin'
    } else {
      payMethosType = 'weixinMiniPayPlugin'
    }
    payment(data.data.id, { paymentPluginId: payMethosType }).then(res => {
      if (res.type == 'success') {
        if (_this.data.payMethodType == 'facePayPlugin') {
          wx.showToast({
            title: '提交成功',
          })
          wx.redirectTo({
            url: '/pages/member/order/details?id=' + _this.data.orderId,
          })
        } else {
          if (res.data.way != 2) {
            _this.submitClick(res)
          } else {
            _this.data.sn = res.data.sn
            wx.showLoading({
              title: '等待支付',
            })
            wx.openEmbeddedMiniProgram({
              appId: 'wx2d00e086c8d08008',
              path: `pages/payment/payment`,
              // envVersion: 'trial',
              extraData: {
                sn: res.data.sn,
                userId: app.globalData.uuid,
                token: app.globalData.token,
                mchName: app.globalData.mchName,
                amount: res.data.amount,
                createDate: res.data.createDate,
                // itemList: data.data.itemList,
                address: data.data.address,
                consignee: data.data.consignee,
                phone: data.data.phone,
                memo: res.data.memo,
                firstEnter: true
              },
              fail: (fail) => {
                wx.hideLoading()
                wx.showModal({
                  title: '支付失败',
                  content: '拉起支付失败，请点击 "允许" 跳转支付',
                  showCancel: false
                })
                this.data.shippingClickFlag = true //开启防双击
              }
            })
          }
        }
      } else {
        wx.showToast({
          icon: "none",
          title: '支付失败',
        })
      }
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: error.content,
      })
      this.data.shippingClickFlag = true //开启防双击
    })
  },
  submitClick(data) {
    var _this = this
    _this.data.sn = data.data.sn
    wx.showLoading({
      title: '加载中...',
    })
    submit({
      paymentPluginId: 'weixinMiniPayPlugin',
      sn: data.data.sn,
      userId: app.globalData.uuid
    }).then(res => {
      wx.hideLoading()
      if (res.type == 'success') {
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function (red) {
            _this.queryClick()
          },
          'fail': function (red) {
            _this.data.shippingClickFlag = true //开启防双击
            wx.showToast({
              icon: "none",
              title: '支付失败',
            })
            wx.redirectTo({
              url: '/pages/member/order/details?id=' + _this.data.orderId,
            })
          }
        })
      } else {
        wx.showToast({
          icon: "none",
          title: '支付失败',
        })
        wx.redirectTo({
          url: '/pages/member/order/details?id=' + _this.data.orderId,
        })
        this.data.shippingClickFlag = true //开启防双击
      }
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: '支付失败',
      })
      wx.redirectTo({
        url: '/pages/member/order/details?id=' + _this.data.orderId,
      })
      this.data.shippingClickFlag = true //开启防双击
    })
  },
  queryClick() {
    var _this = this
    query({
      sn: _this.data.sn
    }).then(res => {
      if (res.type == 'success') {
        wx.redirectTo({
          url: '/pages/goods/submit/complete?id=' + _this.data.orderId,
        })
      } else {
        wx.redirectTo({
          url: '/pages/goods/submit/complete?id=' + _this.data.orderId,
        })
      }
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: error.content,
      })
      this.data.shippingClickFlag = true //开启防双击
    })
  },
  returnClick() {
    this.data.submitType = false
    this.setData({
      submitType: this.data.submitType
    })
  },
  completeClick() {
    var _this = this
    this.data.submitType = false
    _this.data.calculate.paymentVo.forEach(function (item) {
      item.chk = false,
        item.amount = 0
    })
    _this.data.calculate.itemList.forEach(function (item, index) {
      _this.data.check_shippingData.forEach(function (items) {
        if (item.productId == items.productId) {
          _this.data.calculate.itemList.splice(index, 1)
        }
      })
    })
    _this.calculateClick(_this.data.calculate)
    _this.setData({
      calculate: _this.data.calculate,
      submitType: this.data.submitType
    })
  },
  addressClick() {
    var _this = this
    wx.navigateTo({
      url: '/pages/functions/jumpPage/address/address?type=product',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function (data) {
          _this.data.address = data.data
          _this.data.calculate.address = _this.data.address.address
          _this.data.calculate.receiverId = _this.data.address.id
          _this.data.calculate.areaName = _this.data.address.areaName
          _this.data.calculate.consignee = _this.data.address.consignee
          _this.data.calculate.phone = _this.data.address.phone
          _this.setData({
            address: _this.data.address,
            calculate: _this.data.calculate
          })
          _this.calculateClick(_this.data.calculate)
        },
        someEvent: function (data) {
          console.log(data)
        }
      },
    })
  },
  loadBuild(options) {
    var _this = this
    build({
      uuid: app.globalData.uuid,
      bargainBuyId: options.bargainBuyId,
      groupBuyId: options.groupId,
      giftCardId: options.id,
      shopId: options.shopId
    }).then(res => {
      if (res.type == 'success') {
        _this.data.calculate = res.data.order;
        _this.data.order_Details = res.data.order;
        _this.data.order_Details.amountPaid = 0;
        if (!util.isNull(res.data.shippingMethods)) {
          _this.data.shippingMethods = res.data.shippingMethods.split(",")
          _this.data.shippingMethods.forEach(function (item) {
            // if (item == "2") { //开启配送时间
            //   _this.data.deliveryTimeFlag = true
            // }
            if (item == "1") { //到店自提
              wx.getLocation({
                type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
                isHighAccuracy: true,
                success: res => {
                  app.globalData.lat = res.latitude
                  app.globalData.lng = res.longitude
                  _this.data.lat = res.latitude
                  _this.data.lng = res.longitude
                },
                fail: err => {
                  console.log(err)
                }
              })
            }
            if (_this.data.shippingMethods.length > 1 && item == 1) {
              _this.data.shippingMethodType = true
            }
            if (_this.data.shippingMethods.length == 1 && item != 1) {
              _this.data.distributionType = true
            }
          })
        }
        _this.data.consignee = ''
        _this.data.shopId = ''
        _this.data.phone = ''
        if (res.data.order.consignee) {
          _this.data.consignee = res.data.order.consignee
        }
        if (res.data.order.shopId) {
          _this.data.shopId = res.data.order.shopId
          _this.data.shopName = res.data.order.shopName
        }
        if (res.data.order.phone) {
          _this.data.phone = res.data.order.phone
        }
        _this.setData({
          order_Details: _this.data.order_Details,
          delivery: _this.data.delivery,
          shippingMethodType: _this.data.shippingMethodType,
          distributionType: _this.data.distributionType,
          consignee: _this.data.consignee,
          shopId: _this.data.shopId,
          phone: _this.data.phone,
          shopName: _this.data.shopName,
          // deliveryTimeFlag: _this.data.deliveryTimeFlag,
        })
        _this.loadList()
      }
    })
  },
  chooseLeftClick() {
    var _this = this
    this.data.distributionType = true
    _this.data.shippingMethod = 0
    _this.data.calculate.shippingMethod = 0
    _this.calculateClick(_this.data.calculate)
    this.setData({
      distributionType: this.data.distributionType
    })
  },
  chooseRightClick() {
    var _this = this
    this.data.distributionType = false
    _this.data.shippingMethod = 1
    _this.data.calculate.shippingMethod = 1
    _this.calculateClick(_this.data.calculate)
    this.setData({
      distributionType: this.data.distributionType
    })
  },
  loadList() {
    var _this = this
    var defaultAddress = []
    list({
      mchId: app.globalData.mchId
    }).then(res => {
      console.log(res)
      if (res.data.data.length > 0) {
        res.data.data.forEach(function (item) {
          if (item.isDefault == true) {
            defaultAddress.push(item)
          }
        })
      }
      if (!util.isNull(defaultAddress)) {
        _this.data.address = defaultAddress[0]
      }
      if (this.data.address != null) {
        _this.data.calculate.address = _this.data.address.address
        _this.data.calculate.receiverId = _this.data.address.id
        _this.data.calculate.areaName = _this.data.address.areaName
        _this.data.calculate.consignee = _this.data.address.consignee
        _this.data.calculate.phone = _this.data.address.phone
      }
      _this.setData({
        address: _this.data.address,
        calculate: _this.data.calculate
      })
      _this.calculateClick(_this.data.calculate)
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: error.content,
      })
    })
  },
  calculateClick(data) {
    const _this = this
    calculate(data).then(res => {
      _this.data.point = res.data.matchPoint
      _this.data.calculate = res.data.order
      _this.data.bomType = res.data.bomType
      _this.data.paymentVo = res.data.order.paymentVo
      if (!util.isNull(res.data.couponCodeName)) {
        _this.data.couponCodeName = res.data.couponCodeName
        _this.setData({
          couponCodeName: _this.data.couponCodeName
        })
      }
      _this.data.waterType = false
      _this.data.waterStatus = false
      _this.data.tabNumStatus = false
      _this.data.waterPrice = 0
      res.data.order.itemList.forEach(function (item) {
        if (item.subType == 3) {
          _this.data.waterType = true
          _this.data.waterPrice += item.amount
        }
        if (item.subType == 4) {
          _this.data.waterStatus = true
        }

        if (app.DESK_TYPE == 0) {
          _this.data.tabNumber = null
        } else if (item.subType != 5 && app.DESK_TYPE == 1) {
          _this.data.tabNumber = 0
        } else if (item.subType == 5 && app.DESK_TYPE == 1) {
          _this.data.tabNumStatus = true
        }
      })
      // this.data.amount = this.screenClick(res.data)
      _this.data.amount = res.data.amount
      _this.setData({
        point: _this.data.point,
        calculate: _this.data.calculate,
        amount: _this.data.amount,
        paymentVo: _this.data.paymentVo,
        waterType: _this.data.waterType,
        waterStatus: _this.data.waterStatus,
        tabNumber: _this.data.tabNumber,
        tabNumStatus: _this.data.tabNumStatus,
        waterPrice: _this.data.waterPrice,
        bomType: _this.data.bomType
      })
      if (res.data.order.shopId != null) {
        shopFind(res.data.order.shopId).then(res => {
          _this.data.shopName = res.data.shop.name
          _this.data.shopAddress = res.data.shop.address
          _this.setData({
            shopName: _this.data.shopName,
            shopAddress: _this.data.shopAddress
          })
        })
      } else if (_this.data.distributionType == false) {
        this.getShopList()
      }
      // if (this.data.distributionType == false) { //到店自提
      //   this.getInfo()
      // }
      Object.keys(this.data.customerInfo).length == 0 ? this.data.customerInfo.member = {} : ""
      if (this.data.customerInfo.member.name != null) {
        if (res.data.order.shopId != null) {
          _this.data.shopId = res.data.order.shopId
          this.setData({
            shopId: _this.data.shopId
          })
        }
        _this.createClick()
      }
    }
    ).catch(err => {
      console.log(err);
      this.data.shippingClickFlag = true //开启防双击
    })
  },
  screenClick(data) {
    // // 计算自动勾选后的金额
    // var amount = Number(data.amount.toFixed(2))
    // if(data.order.paymentVo.length > 0){
    //   data.order.paymentVo.forEach(function(item){
    //     if(item.chk == true){
    //       amount -= Number(item.amount)
    //     }
    //   })
    //   return amount
    // }else{
    //   return data.amount.toFixed(2)
    // }
  },
  memoClick(data) {
    var _this = this
    _this.data.calculate.memo = data.detail.value
    _this.setData({
      calculate: _this.data.calculate
    })
  },
  changeClick(data) {
    var _this = this
    var paymentPluginId = _this.data.calculate.paymentVo[data.currentTarget.dataset.index].paymentPluginId
    if (_this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk == false) {
      if (_this.data.amount != 0) {
        if (paymentPluginId == 'waterTicketPayPlugin' || paymentPluginId == 'couponCodePayPlugin') {
          var amount = 0
          _this.data.calculate.paymentVo.forEach(function (item) {
            amount += Number(item.amount)
            item.amount = 0
            item.chk = false
          })
          amount = Number(amount) + Number(_this.data.amount)
          _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = _this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance
          _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = true
          _this.data.amount = amount - _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount
        } else {
          if (_this.data.amount >= _this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance) {
            _this.data.amount = (Number(_this.data.amount) - Number(_this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance)).toFixed(2)
            _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = _this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance
          } else {
            _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = _this.data.amount
            _this.data.amount = 0
          }
          _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = true
        }
      } else {
        _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = false;
        wx.showToast({
          icon: "none",
          title: '本商品已无法抵用优惠',
        })
      }
    } else {
      _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = false
      if (_this.data.calculate.paymentVo[data.currentTarget.dataset.index].paymentPluginId == "warehousePayPlugin") {
        _this.data.amount = Number(_this.data.amount) + Number(_this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance)
      } else {
        _this.data.amount = Number(_this.data.amount) + Number(_this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount)
      }
      _this.data.amount = _this.data.amount.toFixed(2)
      _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = 0
    }
    _this.setData({
      calculate: _this.data.calculate,
      amount: _this.data.amount,
    })
  },
  packageClick() {
    this.data.packageType = !this.data.packageType
    this.setData({
      packageType: this.data.packageType
    })
  },
  cenclePackage() {
    this.data.packageType = false
    this.setData({
      packageType: this.data.packageType
    })
  },
  saveClick(data) {
    var _this = this
    _this.data.weexDate = []
    _this.data.weexTime = data.detail.weexTime
    if (data.detail.weexData.length != 0) {
      _this.data.weexDate = data.detail.weexData
    } else {
      _this.data.weexDate = [
        { title: '请选择配送日期' }
      ]
    }
    this.data.packageType = false
    this.setData({
      packageType: this.data.packageType,
      weexDate: this.data.weexDate,
      weexTime: this.data.weexTime
    })
  },
  bucketClick() {
    this.selectComponent('#bucket').isShowClick()
  },
  productsAdd(data) {
    var _this = this
    this.selectComponent('#bucket').closeProduct()
    var itemList = data.detail
    var waterNum = 0
    var waterNumthree = 0
    var waterType = false
    _this.data.calculate.itemList.forEach(function (item) {
      if (item.subType == 4) {
        waterNum += Number(item.quantity)
      }
      if (item.subType == 3) {
        waterNumthree += item.quantity
        waterType = true
      }
    })
    itemList.quantity = Number(waterNum)
    var itemListForm = {
      amount: itemList.price * itemList.quantity,
      availableReturnQuantity: 0,
      availableShippedQuantity: 0,
      cost: 0,
      couponCodeId: null,
      couponCodeQuantity: 0,
      createDate: null,
      discount: 0,
      id: null,
      isGift: false,
      modifyDate: null,
      name: itemList.name,
      orderId: null,
      price: itemList.price,
      productId: itemList.id,
      promotionId: null,
      quantity: itemList.quantity,
      returnQuantity: 0,
      shippedQuantity: 0,
      sn: null,
      spec: itemList.spec,
      subTotal: 0,
      subType: 3,
      thumbnail: itemList.thumbnail,
      unit: null,
      weight: 0
    }
    _this.data.calculate.itemList.forEach(function (item, index) {
      if (item.subType == 3) {
        _this.data.calculate.itemList.splice(index, 1)
      }
    })
    _this.data.calculate.itemList.push(itemListForm)
    _this.calculateClick(_this.data.calculate)
  },
  //配送站点
  siteClick() {
    this.data.siteType = true
    this.setData({
      siteType: this.data.siteType
    })
  },
  cencleSite() {
    this.data.siteType = false
    this.setData({
      siteType: this.data.siteType
    })
  },
  completeSite(data) {
    var _this = this
    this.data.siteType = false
    this.data.shopId = data.detail.from.id
    this.data.shopName = data.detail.from.name
    this.data.shopIndex = data.detail.shopIndex
    _this.data.calculate.shopId = data.detail.from.id
    _this.data.shopAddress = data.detail.from.address
    _this.data.shopAreaName = data.detail.from.areaName
    this.setData({
      siteType: _this.data.siteType,
      shopId: _this.data.shopId,
      shopName: _this.data.shopName,
      shopIndex: _this.data.shopIndex,
      shopAddress: _this.data.shopAddress,
      shopAreaName: _this.data.shopAreaName
    })
  },
  inputConsignee(data) {
    this.data.consignee = data.detail.value
    this.data.calculate.consignee = data.detail.value
    this.setData({
      consignee: this.data.consignee
    })
  },
  input(data) {
    var _this = this
    _this.data.phone = data.detail.value
    _this.data.calculate.phone = data.detail.value
    _this.setData({
      phone: _this.data.phone
    })
  },
  // 手机号弹窗
  savedialogPhoneClick(e) {
    console.log(e)
    this.data.phone = e.detail
    this.setData({
      phone: this.data.phone
    })
  },
  // 线上线下支付
  payMethodClick(data) {
    console.log(data.currentTarget.dataset.type)
    var _this = this;
    if (_this.data.payMethodType == data.currentTarget.dataset.type) {
      _this.data.payMethodType = ''
    } else {
      _this.data.payMethodType = data.currentTarget.dataset.type
    }
    _this.setData({
      payMethodType: _this.data.payMethodType
    })
  },
  formatNumber(num) {
    num = num.toString()
    return num[1] ? num : '0' + num
  },
  GetDateStr(AddDayCount) {
    let dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期
    let y = dd.getFullYear();
    let m = ((dd.getMonth() + 1) < 10 ? '0' + (dd.getMonth() + 1) : (dd.getMonth() + 1));
    let d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate();
    return y + "-" + m + "-" + d;
  },
  myevent(e) {  // 配送时间
    const date = new Date();
    let estimateDateTZ = new Date(this.data.estimateDate).getTime() - 16 * 3600000; //3600000 1小时
    if (e.detail.startTime == "立即送出") {
      this.data.calculate.estimateDate = ""
      this.data.urgent = 1
    } else {
      this.data.urgent = 2
      this.data.calculate.estimateDate = util.datetimeFormatTZ(estimateDateTZ)
    }
    let Month = date.getMonth() + 1
    if (Month.length == 1) {
      Month = '0' + Month
    }
    let dateNum = date.getDate();
    if (e.detail.dateIdx == 0) {
      this.data.estimateDate = this.data.urgent == 1 ? "" : date.getFullYear() + "-" + this.formatNumber(Month) + "-" + this.formatNumber(dateNum) + "T" + e.detail.startTime + ":00Z";
      this.data.deliveryTime = this.data.urgent == 1 ? e.detail.startTime : "今天 " + e.detail.startTime
    } else if (e.detail.dateIdx == 1) {
      let tomorrow = this.GetDateStr(1);
      this.data.estimateDate = tomorrow + "T" + e.detail.startTime + ":00Z";
      this.data.deliveryTime = '明天 ' + e.detail.startTime
    }
    this.data.calculate.urgent = this.data.urgent
    this.data.calculate.estimateDate = this.data.estimateDate
    this.setData({
      calculate: this.data.calculate,
      deliveryTime: this.data.deliveryTime,
      urgent: this.data.urgent,
    })
    this.calculateClick(this.data.calculate)
  },
  delEmpBar(e) {
    this.data.calculate.itemList.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      calculate: this.data.calculate
    })
    this.calculateClick(this.data.calculate)
  },
  tabNumbresClick(data) {
    this.selectComponent('#selectTabNum').isShowClick();
  },
  tabNumbresChange(data) {
    console.log(data);
    this.setData({
      tabNumber: data.detail.tabNum,
      "calculate.num": data.detail.tabNum
    })
  }
})
